<!--
  * 代理商表
  *
  * @Author:    zhoujk
  * @Date:      2025-01-26 06:40:44
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="商户名称" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.companyNameLeftLike" placeholder="商户名称" allow-clear />
      </a-form-item>
      <a-form-item label="开户业务人员" class="smart-query-form-item">
        <CustomSelect
          style="width: 200px"
          v-model:value="queryForm.exhibitionId"
          :placeholder="'请选择开户业务人员'"
          :api="exhibitionApi.queryPage"
          queryParamKey="nameLeftLike"
          :queryParams="exhibitionParams"
          labelField="name,no"
        />
      </a-form-item>
      <a-form-item label="代理商" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.agentName" placeholder="代理商" allow-clear />
        <!-- <AgentPageSelect
          style="width: 200px"
          ref="agentSelect"
          placeholder="请选择上级"
          width="100%"
          v-model:value="queryForm.agentId"
          :leaveFlag="false"
        /> -->
      </a-form-item>
      <a-form-item label="登录账号" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.no" placeholder="登录账号" allow-clear />
      </a-form-item>
      <a-form-item label="状态" class="smart-query-form-item">
        <a-select v-model:value="queryForm.status" style="width: 200px" :options="ZZB_MCH_NO_STATUS" placeholder="请选择状态" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="showForm" type="primary" size="small" v-privilege="'merchant:insert'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <!-- <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.OPERATION.MERCHANT" :refresh="queryData" /> -->
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false">
      <template #bodyCell="{ record, column }">
        <!-- 有图片预览时 注释解开并把下面的'picture'修改成自己的图片字段名即可 -->
        <!-- <template v-if="column.dataIndex === 'picture'">
                  <FilePreview :fileList="text" type="picture" />
                </template> -->

        <!-- 使用字典时 注释解开并把下面的'data-dictionaries'修改成自己的字典字段名即可 有多个字典字段就复制多份同理修改 不然不显示字典 -->
        <!-- 方便修改tag的颜色 orange green purple success processing error default warning -->
        <!-- <template v-if="column.dataIndex === 'data-dictionaries'">
                <a-tag color="cyan">
                  {{ text && text.length > 0 ? text.map((e) => e.valueName).join(',') : '暂无' }}
                </a-tag>
              </template> -->

        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="showForm(record)" type="link" v-privilege="'merchant:update'">编辑</a-button>
            <a-button @click="showDetail(record)" type="link" v-privilege="'merchant:find_id'">查看</a-button>
            <a-button @click="resetPwd(record)" type="link" v-privilege="'merchant:reset_pwd'">密码重置</a-button>
            <a-button @click="goTo('/agent/merchant/regist', record)" type="link" v-privilege="'agent_channel:page_mch'">收款通道</a-button>
            <a-button @click="setRate(record)" type="link" v-privilege="'merchant:ratePage'">查看费率</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <MerchantForm ref="formRef" @reloadList="queryData" />
    <RateList apiType="merchant" ref="rateFormRef" @reloadList="queryData" operateType="view" />
    <MerchantDetail ref="detailRef" @reloadList="queryData" />
    <ResetPwdModal ref="resetPwdRef" @success="queryData" :apiFunction="merchantApi.resetPwd" />
  </a-card>
</template>
<script setup>
  import { reactive, ref, onMounted, createVNode } from 'vue'
  import { useRouter } from 'vue-router'
  import { message, Modal } from 'ant-design-vue'
  import { merchantApi } from '/@/api/business/b-agent/merchant/merchant-api'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import TableOperator from '/@/components/support/table-operator/index.vue'
  import MerchantForm from './merchant-form.vue'
  import RateList from '../agent/rate-list.vue'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import MerchantDetail from './merchant-detail.vue'
  // import ResetPwdModal from './reset-pwd-modal.vue'
  import ResetPwdModal from '/@/components/business/comment/reset-pwd-modal.vue'
  import { TABLE_ID_CONST } from '/@/constants/support/table-id-const.js'
  import { exhibitionApi } from '/@/api/business/b-operation/exhibition/exhibition-api.js'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { ZZB_AUTH_BUSS_TYPE_ENUM, ZZB_ENABLE_STATUS_ENUM, ZZB_EXHIBITION_STATUS_ENUM } from '/@/constants/system/system-const.js'
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
  import { selectDictLabel } from '/@/utils/common'
  import {
    ZZB_MCH_NO_STATUS, //商户状态
  } from '/@/constants/dict'

  /* 路由跳转 */
  const router = useRouter()
  function goTo(url, data) {
    router.push({ path: url, query: { merchantData: JSON.stringify(data) } })
  }
  // ---------------------------- 表格列 ----------------------------
  const statusTypeColorArray = ['orange', 'blue', 'red']

  const columns = ref([
    {
      title: '登录账号',
      dataIndex: 'no',
      ellipsis: true,
    },
    {
      title: '商户名称',
      dataIndex: 'companyName',
      ellipsis: true,
    },
    {
      title: '开户业务人员',
      dataIndex: 'exhibitionName',
      ellipsis: true,
    },
    {
      title: '所属代理商',
      dataIndex: 'oAgentName',
      ellipsis: true,
    },
    {
      title: '商户联系人',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '手机',
      dataIndex: 'phone',
      ellipsis: true,
    },
    {
      title: '地址',
      dataIndex: 'addr',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      customRender: ({ text }) => {
        return selectDictLabel(ZZB_MCH_NO_STATUS, text)
      },
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 180,
    },
  ])

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    companyNameLeftLike: undefined, //商户名称
    exhibitionId: undefined, //开户业务人员
    agentId: undefined, //父级代理商编号
    agentName: undefined, //父级代理商编号
    no: undefined, //商户账号
    status: undefined, //状态，0正常使用，1禁止开代理商，2禁止开商户，3禁止操作人员登录，4系统停止使用，5停止全部收款，6全部禁用
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      let queryResult = await merchantApi.page(queryForm)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }
  const exhibitionParams = reactive({
    showDeletedFlag: false,
    status: ZZB_EXHIBITION_STATUS_ENUM.EXHIBITION_STATUS_NORMAL.value,
    userStatus: ZZB_ENABLE_STATUS_ENUM.ENABLE_STATUS.value,
    authBussType: ZZB_AUTH_BUSS_TYPE_ENUM.AUTH_BUSS_TYPE_OPEN_MERCHANT.value,
  })

  onMounted(queryData)

  // ---------------------------- 添加/修改 ----------------------------
  const formRef = ref()

  function showForm(data) {
    formRef.value.show(data)
  }

  // ---------------------------- 详情 ----------------------------
  const detailRef = ref()

  function showDetail(data) {
    detailRef.value.show(data)
  }

  // ---------------------------- 重置密码 ----------------------------
  const resetPwdRef = ref()
  async function resetPwd(record) {
    if (!resetPwdRef.value) {
      message.error('组件未加载完成，请稍后重试')
      return
    }
    resetPwdRef.value.show(record)
  }
  // ---------------------------- 状态修改 ----------------------------

  // 费率设置表单ref
  const rateFormRef = ref()

  // 设置费率
  async function setRate(record) {
    if (!rateFormRef.value) {
      message.error('组件未加载完成，请稍后重试')
      return
    }
    let data = {
      ...record,
      id: record.oAgentId,
      merchantId: record.id,
    }
    rateFormRef.value.show(data)
  }
</script>
